import { useState, useEffect } from "react";
import { history } from "umi";
import "./DeclineSceneStyles.css";
import Character from "@/components/Character";
import Dialog from "@/components/Dialog";
import Card from "@/components/Card";
import backgroundImage from "@/assets/p1/scenes/decline-background.jpg";
import dialogImage from "@/assets/p1/dialog_background_green.png";
import protagonistImage from "@/assets/p1/characters/protagonist-right.png";
import landlordImage from "@/assets/p1/characters/landlord-right.png";
import landlordLeftImage from "@/assets/p1/characters/landlord.png";
import farmer1ImageLeft from "@/assets/p1/characters/farmer1.png";
import farmer2ImageLeft from "@/assets/p1/characters/farmer2.png";
import front1 from "@/assets/p1/front1-right.png";
import front2 from "@/assets/p1/front2-right.png";
import front3 from "@/assets/p1/front3-right.png";
import back1 from "@/assets/p1/back1.PNG";
import back2 from "@/assets/p1/back2.PNG";
import back3 from "@/assets/p1/back3.PNG";
import left1 from "@/assets/p1/left1.png";
import left2 from "@/assets/p1/left2.png";
import left3 from "@/assets/p1/left3.png";
import right1 from "@/assets/p1/right1.png";
import right2 from "@/assets/p1/right2.png";
import right3 from "@/assets/p1/right3.png";
import horseImage from "@/assets/p1/horse.png";
import oxImage from "@/assets/p1/ox.png";
import sheepImage from "@/assets/p1/sheep.png";
import footprintsImage from "@/assets/p1/footprints.png";
import TreasureBox from "@/components/TreasureBox";
import AchievementList from "@/components/AchievementList";
import magnifierImage from "@/assets/p1/magnifier.png";
import ironImage from "@/assets/p1/iron.png";

const DeclineChapterScene = () => {
	// 在脚印状态中新增一个表示脚印是否被发现的字段
	const [footprintsFound, setFootprintsFound] = useState({
		1: false,
		2: false,
		3: false,
		4: false,
	});

	const [showCard, setShowCard] = useState(false);
	const [declineSuccess, setDeclineSuccess] = useState(false);
	const [dialog1, setDialog1] = useState(false);
	const [dialog2, setDialog2] = useState(false);
	const [gameCard1, setGameCard1] = useState(false);
	const [gameCard2, setGameCard2] = useState(false);
	const [input1, setInput1] = useState("");
	const [input2, setInput2] = useState("");
	const [trail, setTrail] = useState("");
	const [found, setFound] = useState(false);

	const screenWidth = window.innerWidth; // 1707
	const screenHeight = window.innerHeight; // 791
	// 角色初始位置是 initPositionX 和 initPositionY
	const initPositionX = 0.1 * screenWidth;
	const initPositionY = 0.8 * screenHeight;
	const [characterPosition, setCharacterPosition] = useState({
		x: initPositionX,
		y: initPositionY,
	});
	const handlePositionChange = newPosition => {
		setCharacterPosition(newPosition);
	};

	const characterImages = {
		front: [front1, front2, front3, front2],
		left: [left1, left2, left3, left2],
		right: [right1, right2, right3, right2],
		back: [back1, back2, back3, back2]
	};
	const preventArrowKeyScroll = e => {
		if ([37, 38, 39, 40].includes(e.keyCode)) {
			e.preventDefault();
		}
	};
	// 添加一个新的状态存储放大镜的位置
	const [magnifyingGlassPosition, setMagnifyingGlassPosition] = useState({
		x: initPositionX,
		y: initPositionX,
	});
	// 更新放大镜位置的状态
	const handleMouseMove = event => {
		const { clientX, clientY } = event;
		const magnifierOffsetX = 75;
		const magnifierOffsetY = 75;
		setMagnifyingGlassPosition({
			x: clientX - magnifierOffsetX, // 调整偏移量以确保鼠标位于放大镜中心
			y: clientY - magnifierOffsetY,
		});
	};
	const xLandlord = 0.29 * screenWidth;

	const dialogues1 = [
		"发生什么事了？",
		"是他们偷了我的牛、羊、马，还让我赔偿他们的谷物！",
		"我们没偷你的东西！反倒是你家牛踩了我的地还想抵赖！",
		"是啊，你家的马还踩了我家的小麦呢。",
		"仔细询问一番……",
		"明白了，原来是地主家丢了牛、羊、马，农民家的地也被踩坏了，然后地主在农民家发现了丢失的牛和羊，需要算一下赔偿对吧？",
		"现在帮助地主根据脚印的数量计算一下赔偿的倍数吧！",
		"",
	];
	const dialogues2 = ["现在还有一件事，就是帮助地主寻找丢失的马了。"];

	useEffect(() => {
		const { x, y } = characterPosition; // 设置 CSS 变量
		document.documentElement.style.setProperty(
			"--screen-width",
			`${screenWidth}px`
		);
		document.documentElement.style.setProperty(
			"--screen-height",
			`${screenHeight}px`
		);

		// 计算居中视角的滚动位置
		const scrollLeft = x - window.innerWidth / 2;
		const scrollTop = y - (window.innerHeight - initPositionY / 3) / 2;

		// 设置滚动位置
		// 设置滚动行为改为平滑的滚动

		window.scrollTo({
			left: scrollLeft,
			top: scrollTop,
		});
		if (
			Math.sqrt(
				Math.pow(characterPosition.x - xLandlord, 2) +
					Math.pow(characterPosition.y - initPositionY, 2)
			) <= 150 &&
			!gameCard1 &&
			!gameCard2 &&
			!dialog2 &&
			!trail
		) {
			setDialog1(true);
		}
		if (input1 == 2 && input2 == 4 && gameCard2) {
			setTimeout(() => {
				setDeclineSuccess(true);
				setGameCard2(false);
			}, 300);
		}
		if (
			found &&
			Math.abs(x - 0.99 * screenWidth) <= 100 &&
			y < 0.1 * screenHeight
		) {
			history.push("/p1/SmithShopScene");
		}
		window.addEventListener("keydown", preventArrowKeyScroll);

		// useEffect 的清理函数在组件卸载时执行，用来移除事件监听
		return () => {
			window.removeEventListener("keydown", preventArrowKeyScroll);
		};
	}, [input1, input2, characterPosition.x, characterPosition.y]);
	return (
		<div
			className="backgroundImage"
			style={{ backgroundImage: `url(${backgroundImage})` }}
			onMouseMove={trail ? handleMouseMove : () => {}} // 添加鼠标移动事件处理函数
		>
			<TreasureBox />
			<AchievementList />
			{dialog1 && (
				<Dialog
					dialogues={dialogues1}
					backgroundImage={dialogImage}
					triggerIndexEvents={[7]}
					eventHandlers={[
						() => {
							setDialog1(false);
							setGameCard1(true);
						},
					]}
					dialogueImages={[
						{ leftImage: protagonistImage },
						{ rightImage: landlordLeftImage },
						{ rightImage: farmer1ImageLeft },
						{ rightImage: farmer2ImageLeft },
						{ leftImage: protagonistImage },
						{ leftImage: protagonistImage },
					]}
				/>
			)}
			{dialog2 && (
				<Dialog
					dialogues={dialogues2}
					backgroundImage={dialogImage}
					dialogueImages={[{ leftImage: protagonistImage }]}
					triggerIndexEvents={[0]}
					eventHandlers={[
						() => {
							setTrail(true);
							setDialog2(false);
						},
					]}
				/>
			)}

			{declineSuccess && (
				<Card
					onClick={() => {
						setDialog2(true);
						setDeclineSuccess(false);
					}}
					visible={true}
					cardId={3}
					style={{ color: "#3d3d3d", background: "#fff" }}
				>
					<p>获得成就</p>
					<p>衰分</p>
				</Card>
			)}
			{gameCard1 && (
				<div
					className="game"
					onClick={() => {
						setGameCard1(false);
						setGameCard2(true);
					}}
				>
					<div>
						羊 <img className="animal" src={sheepImage} />=
						<img src={footprintsImage} />
					</div>
					<div>
						马 <img className="animal" src={horseImage} />=
						<img src={footprintsImage} />
						<img src={footprintsImage} />
					</div>
					<div>
						牛<img className="animal" src={oxImage} />=
						<img src={footprintsImage} />
						<img src={footprintsImage} />
						<img src={footprintsImage} />
					</div>
				</div>
			)}
			{gameCard2 && (
				<div className="game game2">
					<img className="animal" src={sheepImage} />=
					<input
						value={input1}
						onChange={e => setInput1(e.target.value)}
					/>
					<img className="animal" src={horseImage} />=
					<input
						value={input2}
						onChange={e => setInput2(e.target.value)}
					/>
					<img className="animal" src={oxImage} />
				</div>
			)}
			<Character
				characterImages={characterImages}
				canMove={true}
				characterImage={protagonistImage}
				initPositionX={initPositionX}
				initPositionY={initPositionY}
				onPositionChange={handlePositionChange}
				ifProtagonist="true"
			/>
			<Character
				characterImage={landlordImage}
				initPositionX={xLandlord}
				initPositionY={initPositionY}
			/>
			<Character
				characterImage={farmer1ImageLeft}
				initPositionX={xLandlord + 120}
				initPositionY={initPositionY}
			/>
			<Character
				characterImage={farmer2ImageLeft}
				initPositionX={xLandlord + 240}
				initPositionY={initPositionY}
			/>
			{/* 
                根据放大镜的位置判断是否为脚印添加 'visible' 类 
                要判断放大镜是否在脚印的覆盖范围内，你需要知道脚印的位置。
            */}
			<img
				className={`footprints num1 ${isFootprintVisible(magnifyingGlassPosition, 1) ? "visible" : ""}`}
				src={footprintsImage}
				alt="脚印"
			/>
			<img
				className={`footprints num2 ${isFootprintVisible(magnifyingGlassPosition, 2) ? "visible" : ""}`}
				src={footprintsImage}
				alt="脚印"
			/>
			<img
				className={`footprints num3 ${isFootprintVisible(magnifyingGlassPosition, 3) ? "visible" : ""}`}
				src={footprintsImage}
				alt="脚印"
			/>
			<img
				className={`footprints num4 ${isFootprintVisible(magnifyingGlassPosition, 4) ? "visible" : ""}`}
				src={ironImage}
				alt="马蹄铁"
			/>
			<img
				src={magnifierImage}
				className={"magnifierImage"}
				style={{
					left: `${magnifyingGlassPosition.x}px`,
					top: `${magnifyingGlassPosition.y}px`,
					display: trail ? "block" : "none",
				}}
			/>
			{showCard && (
				<div
					onClick={() => {
						setShowCard(false);
					}}
					className={"iron"}
				>
					发现了一个马蹄铁
				</div>
			)}
		</div>
	);

	function isFootprintVisible(magnifyingPosition, footprintNumber) {
		const footprintPositions = {
			1: { x: 0.7 * screenWidth, y: 0.82 * screenHeight },
			2: { x: 0.85 * screenWidth, y: 0.82 * screenHeight },
			3: { x: 0.99 * screenWidth, y: 0.6 * screenHeight },
			4: { x: 0.99 * screenWidth, y: 0.25 * screenHeight },
		};
		const footprint = footprintPositions[footprintNumber];
		const range = 50;
		// 获取当前页面的水平滚动位置
		const scrollX =
			window.pageXOffset || document.documentElement.scrollLeft;
		// 获取当前页面的垂直滚动位置
		const scrollY =
			window.pageYOffset || document.documentElement.scrollTop;
		const x = magnifyingPosition.x + scrollX;
		const y = magnifyingPosition.y + scrollY;
		const isVisible =
			x >= footprint.x - range &&
			x <= footprint.x + range &&
			y >= footprint.y - range &&
			y <= footprint.y + range;

		if (footprintNumber == 4 && isVisible && !footprintsFound[4]) {
			// 更新状态为找到
			setFootprintsFound(prevFound => ({ ...prevFound, 4: true }));
			// 触发想要执行的事件
			handleFootprintFound();
		}
		return isVisible;
	}
	// 定义要触发的事件
	function handleFootprintFound() {
		setTimeout(() => {
			setShowCard(true);
			setFound(true);
		}, 500);
	}
};
export default DeclineChapterScene;
